﻿#include "HUDTestDrive.h"
#include "HUD.h"
#include "TextUtil.h"
#include <osg/ref_ptr>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>

HUDTestDrive::HUDTestDrive(void)
{
}

HUDTestDrive::~HUDTestDrive(void)
{
}

int HUDTestDrive::Test()
{
	osg::ref_ptr<osg::Node> scene = osgDB::readNodeFile("t72-tank_des.flt");	
	if (!scene)
	{
		osg::notify(osg::NOTICE)<<"No model loaded"<<std::endl;
		return 1;
	}
	osgViewer::Viewer viewer;
	viewer.setSceneData(scene.get());
	//viewer.setUpViewAcrossAllScreens();
	viewer.setUpViewOnSingleScreen();

	osgViewer::Viewer::Windows windows;
	viewer.getWindows(windows);
	if (windows.empty()) return 1;

	//create HUD
	osg::Geode* geode = createText2D(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);
	osg::Camera* hudCamera = HUD::create(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);
	hudCamera->addChild(geode);
	// set up cameras to render on the first window available.
	hudCamera->setGraphicsContext(windows[0]);
	hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);

	//root->addChild(hudCamera);
	viewer.addSlave(hudCamera, false);
	return viewer.run();	
}

osg::Geode* HUDTestDrive::createText2D(int x, int y, int width, int height)
{
	osg::Geode* geode = new osg::Geode();

	std::string xjlFont("fonts/xjlFont.ttf");

	// turn lighting off for the text and disable depth test to ensure it's always ontop.
	osg::StateSet* stateset = geode->getOrCreateStateSet();
	stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	//osg::Vec3 position(x, y, 0.0f);
	osg::Vec3 position(x+width/2, y+height*3/4, 0.0f);
	//osg::Vec3 position(150.0f,800.0f,0.0f);
	osg::Vec3 delta(0.0f,-height/4,0.0f);
	{
		osgText::Text* text = new  osgText::Text;
		geode->addDrawable( text );
		text->setFont(xjlFont);
		text->setPosition(position);
		text->setCharacterSize(60.0f);
		text->setAlignment(osgText::TextBase::CENTER_TOP);
		TextUtil::createContent(*text, "平显很简单 :-)\n"
			"你需要做的只是在（场景子树）这里键入文本.\n"
			"然后把相机放在上面来创建正交投影.");

		position += delta;
	}
	{
		osgText::Text* text = new  osgText::Text;
		geode->addDrawable( text );
		text->setFont(xjlFont);
		text->setPosition(position);
		text->setCharacterSize(60.0f);
		text->setAlignment(osgText::TextBase::CENTER_TOP);
		text->setText("Set the Camera's ReferenceFrame to ABSOLUTE_RF to ensure\n"
			"it remains independent from any external model view matrices.\n"
			"And set the Camera's clear mask to just clear the depth buffer.\n"
			"And finally set the Camera's RenderOrder to POST_RENDER\n"
			"to make sure it's drawn last.");
	}

	geode->addDrawable(HUD::BoundingBox(geode));	
	return geode;
}